﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace InventoryManager
{
    public partial class DatabaseEditorForm : Form
    {
        private string _connectionString;
        private MySqlConnection _connection;

        private Timer _timer;
        private int _blinkCount;

        private bool _editingProduct;
        private bool _editingCustomer;
        private bool _editingSeller;

        private string _oldProductName;
        private string _oldProductDimension;

        private string _oldCoustomerName;
        private string _oldSellerName;

        public DatabaseEditorForm(string connectionString)
        {
            _editingProduct = false;
            _editingCustomer = false;
            _editingSeller = false;

            InitializeComponent();
            _connectionString = connectionString;

            _connection = new MySqlConnection(_connectionString);

            LoadProductName();
            LoadCustomerName();
            LoadSellerName();
        }

        #region LoadData

        private void LoadProductName()
        {
            try
            {
                _connection = new MySqlConnection(_connectionString);
                _connection.Open();

                string query = "SELECT DISTINCT Name FROM product";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                ProductComboBox.Items.Clear();
                DimensionComboBox.Items.Clear();

                foreach (DataRow row in dataTable.Rows)
                    ProductComboBox.Items.Add(row.ItemArray[0].ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        private void LoadCustomerName()
        {
            try
            {
                _connection.Open();

                string query = "SELECT Name, CustomerID FROM customer ORDER BY CustomerID ASC";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                CustomerNameComboBox.Items.Clear();

                foreach (DataRow row in dataTable.Rows)
                    CustomerNameComboBox.Items.Add(row.ItemArray[0].ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        private void LoadSellerName()
        {
            try
            {
                _connection.Open();

                string query = "SELECT Name FROM seller";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                SellerNameComboBox.Items.Clear();

                foreach (DataRow row in dataTable.Rows)
                    SellerNameComboBox.Items.Add(row.ItemArray[0].ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        #endregion

        #region ComboBoxEvent

        private void CustomerNameComboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            EditCustomerRegionGrpBox.Visible = true;
            RemoveCustomerNameButton.Visible = true;
            EditCustomerNameButton.Visible = true;

            try
            {
                string customerName = CustomerNameComboBox.Items[CustomerNameComboBox.SelectedIndex].ToString();

                if (sender != null)
                    _connection.Open();

                string query = "SELECT * FROM customer WHERE Name = \'" + customerName + "\'";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                CustomerAddressTextBox.Text = dataTable.Rows[0][2].ToString();
                CustomerPhoneTextBox.Text = dataTable.Rows[0][3].ToString();
                CustomerFaxTextBox.Text = dataTable.Rows[0][4].ToString();

                CustomerIDLabel.Text = Int32.Parse(dataTable.Rows[0][0].ToString()).ToString("D3");
                TaxIDTextBox.Text = dataTable.Rows[0][5].ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (sender != null)
                    _connection.Close();
            }
        }

        private void SellerNameComboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            EditSellerRegionGrpBox.Visible = true;
            RemoveSellerNameButton.Visible = true;
            EditSellerNameButton.Visible = true;

            try
            {
                string sellerName = SellerNameComboBox.Items[SellerNameComboBox.SelectedIndex].ToString();

                if (sender != null)
                    _connection.Open();

                string query = "SELECT * FROM seller WHERE Name = \'" + sellerName + "\'";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                SellerAddressTextBox.Text = dataTable.Rows[0][1].ToString();
                SellerPhoneTextBox.Text = dataTable.Rows[0][2].ToString();
                SellerFaxTextBox.Text = dataTable.Rows[0][3].ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (sender != null)
                    _connection.Close();
            }
        }

        private void ProductComboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            EditProductRegionGrpBox.Visible = true;
            RemoveProductButton.Visible = true;
            EditProductButton.Visible = true;

            try
            {
                string selectedProduct = ProductComboBox.Items[ProductComboBox.SelectedIndex].ToString();

                _connection.Open();

                string query = "SELECT Dimension FROM product WHERE Name = \'" + selectedProduct + "\' ORDER BY Dimension";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                DimensionComboBox.Items.Clear();

                foreach (DataRow row in dataTable.Rows)
                    DimensionComboBox.Items.Add(row.ItemArray[0].ToString());

                DimensionComboBox.SelectedIndex = 0;
                DimensionComboBox_SelectionChangeCommitted(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        private void DimensionComboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            try
            {
                string selectedProduct = ProductComboBox.Items[ProductComboBox.SelectedIndex].ToString();
                string selectedDimension = DimensionComboBox.Items[DimensionComboBox.SelectedIndex].ToString();

                if (sender != null)
                    _connection.Open();

                string query = "SELECT Classifier, Weight, PricePerWeight, PricePerItem, ItemsRemain, ItemsRemainVat FROM product WHERE Name = \'" + selectedProduct + "\' " +
                    "AND Dimension = \'" + selectedDimension + "\'";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                UnitTextBox.Text = dataTable.Rows[0][0].ToString();

                string weight = dataTable.Rows[0][1].ToString();
                string pricePerWeight = dataTable.Rows[0][2].ToString();
                string pricePerItem = dataTable.Rows[0][3].ToString();

                if (pricePerWeight == "")
                {
                    WeightAvailableCheckBox.Checked = false;
                    EnableOrDisableAllWeightFields(false);

                    WeightPerUnitNumericUpDown.Value = 0;
                    PricePerWeightNumericUpDown.Value = 0;
                }
                else
                {
                    WeightAvailableCheckBox.Checked = true;
                    EnableOrDisableAllWeightFields(true);

                    WeightPerUnitNumericUpDown.Value = Convert.ToDecimal(weight);
                    PricePerWeightNumericUpDown.Value = Convert.ToDecimal(pricePerWeight);
                }
                if (pricePerItem == "")
                {
                    UnitAvailableCheckBox.Checked = false;
                    EnableOrDisableAllUnitFileds(false);

                    PricePerUnitNumericUpDown.Value = 0;
                }
                else
                {
                    UnitAvailableCheckBox.Checked = true;
                    EnableOrDisableAllUnitFileds(true);

                    PricePerUnitNumericUpDown.Value = Convert.ToDecimal(pricePerItem);
                }

                int itemsRemain = Int32.Parse(dataTable.Rows[0][4].ToString());
                int itemsRemainVat = Int32.Parse(dataTable.Rows[0][5].ToString());

                ItemsRemainNumericUpDown.Value = itemsRemain;
                ItemsRemainVatNumericUpDown.Value = itemsRemainVat;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (sender != null)
                    _connection.Close();
            }
        }

        #endregion

        #region SaveButtonEvent

        private void SaveProductButton_Click(object sender, EventArgs e)
        {
            try
            {
                bool success = true;

                if (UnitTextBox.Text == "")
                {
                    UnitTextBox.BackColor = Color.Red;
                    success = false;
                }
                if (!WeightAvailableCheckBox.Checked && !UnitAvailableCheckBox.Checked)
                {
                    WeightAvailableCheckBox.BackColor = Color.Red;
                    UnitAvailableCheckBox.BackColor = Color.Red;
                    success = false;
                }

                if (!success)
                    return;

                string productName = ProductComboBox.Items[ProductComboBox.SelectedIndex].ToString();
                string productDimension = DimensionComboBox.Items[DimensionComboBox.SelectedIndex].ToString();

                _connection.Open();

                MySqlCommand updateCmd = _connection.CreateCommand();

                updateCmd.CommandText = "UPDATE product SET Classifier = \'" + UnitTextBox.Text
                    + "\', ItemsRemain = \'" + ItemsRemainNumericUpDown.Value.ToString()
                    + "\', ItemsRemainVat = \'" + ItemsRemainVatNumericUpDown.Value.ToString()
                    + "\' WHERE Name = \'" + productName + "\' AND Dimension = \'" + productDimension + "\'";

                updateCmd.ExecuteNonQuery();

                if (WeightAvailableCheckBox.Checked)
                {
                    updateCmd.CommandText = "UPDATE product SET Weight = \'" + WeightPerUnitNumericUpDown.Value.ToString()
                    + "\', PricePerWeight = \'" + PricePerWeightNumericUpDown.Value.ToString()
                    + "\' WHERE Name = \'" + productName + "\' AND Dimension = \'" + productDimension + "\'";
                }
                else
                {
                    updateCmd.CommandText = "UPDATE product SET Weight = NULL, PricePerWeight = NULL"
                    + " WHERE Name = \'" + productName + "\' AND Dimension = \'" + productDimension + "\'";
                }

                updateCmd.ExecuteNonQuery();

                if (UnitAvailableCheckBox.Checked)
                {
                    updateCmd.CommandText = "UPDATE product SET PricePerItem = \'" + PricePerUnitNumericUpDown.Value.ToString()
                    + "\' WHERE Name = \'" + productName + "\' AND Dimension = \'" + productDimension + "\'";
                }
                else
                {
                    updateCmd.CommandText = "UPDATE product SET PricePerItem = NULL"
                    + " WHERE Name = \'" + productName + "\' AND Dimension = \'" + productDimension + "\'";
                }

                updateCmd.ExecuteNonQuery();

                ProductComboBox.Enabled = true;
                DimensionComboBox.Enabled = true;
                AddProductButton.Visible = true;
                EditProductButton.Visible = true;

                (new ErrorAndCompleteFrom()).ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        private void SaveCustomerButton_Click(object sender, EventArgs e)
        {
            try
            {
                string customerName = CustomerNameComboBox.Items[CustomerNameComboBox.SelectedIndex].ToString();

                _connection.Open();

                MySqlCommand updateCmd = _connection.CreateCommand();

                updateCmd.CommandText = "UPDATE customer SET Address = \'" + CustomerAddressTextBox.Text
                    + "\', Phone = \'" + CustomerPhoneTextBox.Text + "\', Fax = \'" + CustomerFaxTextBox.Text
                    + "\', TaxID = \'" + TaxIDTextBox.Text
                    + "\' WHERE Name = \'" + customerName + "\'";

                updateCmd.ExecuteNonQuery();

                CustomerNameComboBox.Enabled = true;
                AddCustomerNameButton.Visible = true;
                EditCustomerNameButton.Visible = true;

                (new ErrorAndCompleteFrom()).ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        private void SaveSellerButton_Click(object sender, EventArgs e)
        {
            try
            {
                string sellerName = SellerNameComboBox.Items[SellerNameComboBox.SelectedIndex].ToString();

                _connection.Open();

                MySqlCommand updateCmd = _connection.CreateCommand();

                updateCmd.CommandText = "UPDATE seller SET Address = \'" + SellerAddressTextBox.Text 
                    + "\', Phone = \'" + SellerPhoneTextBox.Text + "\', Fax = \'" + SellerFaxTextBox.Text 
                    + "\' WHERE Name = \'" + sellerName + "\'";

                updateCmd.ExecuteNonQuery();

                SellerNameComboBox.Enabled = true;
                AddSellerNameButton.Visible = true;
                EditSellerNameButton.Visible = true;

                (new ErrorAndCompleteFrom()).ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        #endregion

        #region ValidateData

        private void EnableOrDisableAllWeightFields(bool enable)
        {
            WeightPerUnitLabel.Enabled = enable;
            WeightPerUnitNumericUpDown.Enabled = enable;
            KgLabel.Enabled = enable;

            PricePerWeightLabel.Enabled = enable;
            PricePerWeightNumericUpDown.Enabled = enable;
            BahtWeightLabel.Enabled = enable;
        }

        private void EnableOrDisableAllUnitFileds(bool enable)
        {
            PricePerUnitLabel.Enabled = enable;
            PricePerUnitNumericUpDown.Enabled = enable;
            BahtUnitLabel.Enabled = enable;
        }

        private void WeightAvailableCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            EnableOrDisableAllWeightFields(WeightAvailableCheckBox.Checked);
            WeightAvailableCheckBox.BackColor = Color.White;
            UnitAvailableCheckBox.BackColor = Color.White;
        }

        private void UnitAvailableCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            EnableOrDisableAllUnitFileds(UnitAvailableCheckBox.Checked);
            WeightAvailableCheckBox.BackColor = Color.White;
            UnitAvailableCheckBox.BackColor = Color.White;
        }

        private void UnitTextBox_TextChanged(object sender, EventArgs e)
        {
            UnitTextBox.BackColor = Color.White;
        }

        #endregion

        #region AddRemoveEditProduct

        private void AddProductButton_Click(object sender, EventArgs e)
        {
            AddProductForm addProductForm = new AddProductForm(ProductComboBox);
            switch (addProductForm.ShowDialog())
            {
                case DialogResult.OK:

                    string productName;
                    string productDimension;

                    productName = addProductForm.productName;
                    productDimension = addProductForm.productDimension;

                    AddNewProduct(productName, productDimension);
                    break;
                default:
                    break;
            }
        }

        private void RemoveProductButton_Click(object sender, EventArgs e)
        {
            ConfirmOperationFrom conFirmDeleteForm = new ConfirmOperationFrom();
            switch (conFirmDeleteForm.ShowDialog())
            {
                case DialogResult.OK:
                    try
                    {
                        _connection.Open();

                        MySqlCommand deleteCmd = _connection.CreateCommand();

                        deleteCmd.CommandText = "DELETE FROM product WHERE Name = \'"
                            + ProductComboBox.Items[ProductComboBox.SelectedIndex].ToString() + "\' AND Dimension = \'"
                            + DimensionComboBox.Items[DimensionComboBox.SelectedIndex].ToString() + "\'";

                        deleteCmd.ExecuteNonQuery();

                        _connection.Close();

                        LoadProductName();

                        EditProductRegionGrpBox.Visible = false;
                        RemoveProductButton.Visible = false;
                        EditProductButton.Visible = false;

                        ProductComboBox.Enabled = true;
                        DimensionComboBox.Enabled = true;
                        AddProductButton.Visible = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        _connection.Close();
                    }
                    break;
                default:
                    break;
            }
        }

        private void EditProductButton_Click(object sender, EventArgs e)
        {
            if (!_editingProduct)
            {
                _oldProductName = ProductComboBox.Items[ProductComboBox.SelectedIndex].ToString();
                _oldProductDimension = DimensionComboBox.Items[DimensionComboBox.SelectedIndex].ToString();

                ProductComboBox.DropDownStyle = ComboBoxStyle.Simple;
                DimensionComboBox.DropDownStyle = ComboBoxStyle.Simple;
                AddProductButton.Visible = false;
                RemoveProductButton.Visible = false;
                EditProductRegionGrpBox.Visible = false;

                _editingProduct = true;

                EditProductButton.BackgroundImage = global::InventoryManager.Properties.Resources.Save;
            }
            else
            {
                string newProductName = ProductComboBox.Text;
                string newProductDimension = DimensionComboBox.Text;

                ProductComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                DimensionComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                AddProductButton.Visible = true;
                RemoveProductButton.Visible = true;
                EditProductRegionGrpBox.Visible = true;

                _editingProduct = false;
                EditProductButton.BackgroundImage = global::InventoryManager.Properties.Resources.Add_1;

                EditProduct(_oldProductName, _oldProductDimension,
                    newProductName, newProductDimension);
            }
        }

        private void AddNewProduct(string productName, string productDimension)
        {
            try
            {
                _connection.Open();

                string query = "SELECT Name, Dimension FROM product WHERE Name = \'"
                    + productName + "\' AND Dimension = \'" + productDimension + "\'";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                _connection.Close();

                if (dataTable.Rows.Count == 0)
                {
                    _connection.Open();

                    MySqlCommand insertCmd = _connection.CreateCommand();

                    insertCmd.CommandText = "INSERT INTO product SET Name = \'"
                        + productName + "\', Dimension = \'" + productDimension + "\'";

                    insertCmd.ExecuteNonQuery();

                    _connection.Close();

                    LoadProductName();

                    ProductComboBox.Enabled = false;
                    DimensionComboBox.Enabled = false;
                    AddProductButton.Visible = false;
                }

                ProductComboBox.SelectedItem = productName;
                ProductComboBox_SelectionChangeCommitted(null, null);
                DimensionComboBox.SelectedItem = productDimension;
                DimensionComboBox_SelectionChangeCommitted(null, null);

                if (dataTable.Rows.Count == 0)
                {
                    ProductComboBox.Enabled = false;
                    DimensionComboBox.Enabled = false;
                    AddProductButton.Visible = false;
                    EditProductButton.Visible = false;

                    WeightAvailableCheckBox.Checked = true;
                    UnitAvailableCheckBox.Checked = true;

                    _blinkCount = 0;
                    _timer = new Timer();
                    _timer.Interval = 300;
                    _timer.Tick += new EventHandler(timer_Tick);
                    _timer.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        private void EditProduct(string oldProductName, string oldProductDimension,
            string newProductName, string newProductDimension)
        {
            try
            {
                _connection.Open();

                string query = "SELECT Name, Dimension FROM product WHERE Name = \'"
                    + newProductName + "\' AND Dimension = \'" + newProductDimension + "\'";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                _connection.Close();

                if (dataTable.Rows.Count == 0)
                {
                    _connection.Open();

                    MySqlCommand updateCmd = _connection.CreateCommand();

                    updateCmd.CommandText = "UPDATE product SET Name = \'" + newProductName
                    + "\', Dimension = \'" + newProductDimension
                    + "\' WHERE Name = \'" + oldProductName + "\' AND Dimension = \'"
                    + oldProductDimension + "\'";

                    updateCmd.ExecuteNonQuery();

                    updateCmd.CommandText = "UPDATE orderiddescription SET ProductName = \'" + newProductName
                    + "\', Dimension = \'" + newProductDimension
                    + "\' WHERE ProductName = \'" + oldProductName + "\' AND Dimension = \'"
                    + oldProductDimension + "\'";

                    updateCmd.ExecuteNonQuery();

                    updateCmd.CommandText = "UPDATE requisitioniddescription SET ProductName = \'" + newProductName
                    + "\', Dimension = \'" + newProductDimension
                    + "\' WHERE ProductName = \'" + oldProductName + "\' AND Dimension = \'"
                    + oldProductDimension + "\'";

                    updateCmd.ExecuteNonQuery();

                    updateCmd.CommandText = "UPDATE invoiceiddescription SET ProductName = \'" + newProductName
                    + "\', Dimension = \'" + newProductDimension
                    + "\' WHERE ProductName = \'" + oldProductName + "\' AND Dimension = \'"
                    + oldProductDimension + "\'";

                    updateCmd.ExecuteNonQuery();

                    _connection.Close();

                    LoadProductName();
                }

                ProductComboBox.SelectedItem = newProductName;
                ProductComboBox_SelectionChangeCommitted(null, null);
                DimensionComboBox.SelectedItem = newProductDimension;
                DimensionComboBox_SelectionChangeCommitted(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }

        #endregion

        #region AddRemoveEditCustomer

        private void AddCustomerNameButton_Click(object sender, EventArgs e)
        {
            AddCustomerOrSellerForm addCustomerForm = new AddCustomerOrSellerForm(true);
            switch (addCustomerForm.ShowDialog())
            {
                case DialogResult.OK:

                    string customerName = addCustomerForm.customerOrSellerName;

                    AddNewCustomerOrSeller(true, customerName);
                    break;
                default:
                    break;
            }
        }

        private void RemoveCustomerNameButton_Click(object sender, EventArgs e)
        {
            ConfirmOperationFrom conFirmDeleteForm = new ConfirmOperationFrom();
            switch (conFirmDeleteForm.ShowDialog())
            {
                case DialogResult.OK:
                    try
                    {
                        _connection.Open();

                        MySqlCommand deleteCmd = _connection.CreateCommand();

                        deleteCmd.CommandText = "DELETE FROM customer WHERE Name = \'"
                            + CustomerNameComboBox.Items[CustomerNameComboBox.SelectedIndex].ToString() + "\'";

                        deleteCmd.ExecuteNonQuery();

                        _connection.Close();

                        LoadCustomerName();

                        EditCustomerRegionGrpBox.Visible = false;
                        RemoveCustomerNameButton.Visible = false;
                        EditCustomerNameButton.Visible = false;

                        CustomerNameComboBox.Enabled = true;
                        AddCustomerNameButton.Visible = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        _connection.Close();
                    }
                    break;
                default:
                    break;
            }
        }

        private void EditCustomerName_Click(object sender, EventArgs e)
        {
            if (!_editingCustomer)
            {
                _oldCoustomerName = CustomerNameComboBox.Items[CustomerNameComboBox.SelectedIndex].ToString();

                CustomerNameComboBox.DropDownStyle = ComboBoxStyle.Simple;
                AddCustomerNameButton.Visible = false;
                RemoveCustomerNameButton.Visible = false;
                EditCustomerRegionGrpBox.Visible = false;

                _editingCustomer = true;

                EditCustomerNameButton.BackgroundImage = global::InventoryManager.Properties.Resources.Save;
            }
            else
            {
                string newCustomerName = CustomerNameComboBox.Text;

                CustomerNameComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                AddCustomerNameButton.Visible = true;
                RemoveCustomerNameButton.Visible = true;
                EditCustomerRegionGrpBox.Visible = true;

                _editingCustomer = false;

                EditCustomerNameButton.BackgroundImage = global::InventoryManager.Properties.Resources.Add_1;

                EditCustomerOrSellerName(true, _oldCoustomerName, newCustomerName);
            }
        }

        #endregion

        #region AddRemoveEditSeller

        private void AddSellerNameButton_Click(object sender, EventArgs e)
        {
            AddCustomerOrSellerForm addSellerForm = new AddCustomerOrSellerForm(false);
            switch (addSellerForm.ShowDialog())
            {
                case DialogResult.OK:

                    string sellerName = addSellerForm.customerOrSellerName;
                    AddNewCustomerOrSeller(false, sellerName);
                    break;
                default:
                    break;
            }
        }

        private void RemoveSellerNameButton_Click(object sender, EventArgs e)
        {
            ConfirmOperationFrom conFirmDeleteForm = new ConfirmOperationFrom();
            switch (conFirmDeleteForm.ShowDialog())
            {
                case DialogResult.OK:
                    try
                    {
                        _connection.Open();

                        MySqlCommand deleteCmd = _connection.CreateCommand();

                        deleteCmd.CommandText = "DELETE FROM seller WHERE Name = \'"
                            + SellerNameComboBox.Items[SellerNameComboBox.SelectedIndex].ToString() + "\'";

                        deleteCmd.ExecuteNonQuery();

                        _connection.Close();

                        LoadSellerName();

                        EditSellerRegionGrpBox.Visible = false;
                        RemoveSellerNameButton.Visible = false;
                        EditSellerNameButton.Visible = false;

                        SellerNameComboBox.Enabled = true;
                        AddSellerNameButton.Visible = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        _connection.Close();
                    }
                    break;
                default:
                    break;
            }
        }

        private void EditSellerName_Click(object sender, EventArgs e)
        {
            if (!_editingSeller)
            {
                _oldSellerName = SellerNameComboBox.Items[SellerNameComboBox.SelectedIndex].ToString();

                SellerNameComboBox.DropDownStyle = ComboBoxStyle.Simple;
                AddSellerNameButton.Visible = false;
                RemoveSellerNameButton.Visible = false;
                EditSellerRegionGrpBox.Visible = false;

                _editingSeller = true;

                EditSellerNameButton.BackgroundImage = global::InventoryManager.Properties.Resources.Save;
            }
            else
            {
                string newSellerName = SellerNameComboBox.Text;

                SellerNameComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                AddSellerNameButton.Visible = true;
                RemoveSellerNameButton.Visible = true;
                EditSellerRegionGrpBox.Visible = true;

                _editingSeller = false;

                EditSellerNameButton.BackgroundImage = global::InventoryManager.Properties.Resources.Add_1;

                EditCustomerOrSellerName(false, _oldSellerName, newSellerName);
            }
        }

        #endregion

        void timer_Tick(object sender, EventArgs e)
        {
            if (_blinkCount % 2 == 1)
            {
                switch (DatabaseEditorTabControl.SelectedIndex)
                {
                    case 0:
                        EditProductRegionGrpBox.BackColor = Color.White;
                        break;
                    case 1:
                        EditCustomerRegionGrpBox.BackColor = Color.White;
                        break;
                    default:
                        EditSellerRegionGrpBox.BackColor = Color.White;
                        break;
                }
            }
            else
            {
                switch (DatabaseEditorTabControl.SelectedIndex)
                {
                    case 0:
                        EditProductRegionGrpBox.BackColor = Color.FromArgb(192, 255, 192);
                        break;
                    case 1:
                        EditCustomerRegionGrpBox.BackColor = Color.FromArgb(192, 255, 192);
                        break;
                    default:
                        EditSellerRegionGrpBox.BackColor = Color.FromArgb(192, 255, 192);
                        break;
                }
            }
            _blinkCount++;
            if (_blinkCount == 6)
                _timer.Stop();
        }

        private void AddNewCustomerOrSeller(bool customerMode, string name)
        {
            try
            {
                bool contains = false;

                if (customerMode)
                {
                    if (CustomerNameComboBox.Items.Contains(name))
                        contains = true;
                    else
                    {
                        _connection.Open();

                        MySqlCommand insertCmd = _connection.CreateCommand();

                        insertCmd.CommandText = "INSERT INTO customer SET Name = \'"
                            + name + "\'";

                        insertCmd.ExecuteNonQuery();

                        _connection.Close();

                        LoadCustomerName();

                        CustomerNameComboBox.Enabled = false;
                        AddCustomerNameButton.Visible = false;
                    }

                    CustomerNameComboBox.SelectedItem = name;
                    CustomerNameComboBox_SelectionChangeCommitted(null, null);

                    if (!contains)
                    {
                        CustomerNameComboBox.Enabled = false;
                        AddCustomerNameButton.Visible = false;
                        EditCustomerNameButton.Visible = false;

                        _blinkCount = 0;
                        _timer = new Timer();
                        _timer.Interval = 300;
                        _timer.Tick += new EventHandler(timer_Tick);
                        _timer.Start();
                    }
                }
                else
                {
                    if (SellerNameComboBox.Items.Contains(name))
                        contains = true;
                    else
                    {
                        _connection.Open();

                        MySqlCommand insertCmd = _connection.CreateCommand();

                        insertCmd.CommandText = "INSERT INTO seller SET Name = \'"
                            + name + "\'";

                        insertCmd.ExecuteNonQuery();

                        _connection.Close();

                        LoadSellerName();

                        SellerNameComboBox.Enabled = false;
                        AddSellerNameButton.Visible = false;
                    }

                    SellerNameComboBox.SelectedItem = name;
                    SellerNameComboBox_SelectionChangeCommitted(null, null);

                    if (!contains)
                    {
                        SellerNameComboBox.Enabled = false;
                        AddSellerNameButton.Visible = false;
                        EditSellerNameButton.Visible = false;

                        _blinkCount = 0;
                        _timer = new Timer();
                        _timer.Interval = 300;
                        _timer.Tick += new EventHandler(timer_Tick);
                        _timer.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void EditCustomerOrSellerName(bool customerMode, string oldName, string newName)
        {
            try
            {
                _connection.Open();

                string query;
                if (customerMode)
                    query = "SELECT Name FROM customer WHERE Name = \'" + newName + "\'";
                else
                    query = "SELECT Name FROM seller WHERE Name = \'" + newName + "\'";

                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, _connection);

                DataTable dataTable = new DataTable();
                mySqlDataAdapter.Fill(dataTable);

                _connection.Close();

                if (dataTable.Rows.Count == 0)
                {
                    _connection.Open();

                    MySqlCommand updateCmd = _connection.CreateCommand();

                    if (customerMode)
                    {
                        updateCmd.CommandText = "UPDATE customer SET Name = \'" + newName
                            + "\' WHERE Name = \'" + oldName + "\'";
                        updateCmd.ExecuteNonQuery();
                        _connection.Close();

                        LoadCustomerName();
                    }
                    else
                    {
                        updateCmd.CommandText = "UPDATE seller SET Name = \'" + newName
                            + "\' WHERE Name = \'" + oldName + "\'";
                        updateCmd.ExecuteNonQuery();
                        _connection.Close();

                        LoadSellerName();
                    }
                }
                if (customerMode)
                {
                    CustomerNameComboBox.SelectedItem = newName;
                    CustomerNameComboBox_SelectionChangeCommitted(null, null);
                }
                else
                {
                    SellerNameComboBox.SelectedItem = newName;
                    SellerNameComboBox_SelectionChangeCommitted(null, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                _connection.Close();
            }
        }
    }
}
